#!/usr/bin/env python3

import typing
import logging
import rich.box
import rich.columns
import rich.containers
import rich.layout
import rich.live
import rich.table
import rich.traceback
import trio

import rich
import rich.pretty
import rich.text

from cdp import debugger, runtime
from arkdebug import (
    STDERR,
    STDOUT,
    ArkDebugger,
    ArkDebuggerLive,
    ArkConnectError,
)

LOG: logging.Logger = logging.getLogger("arkdebug")


def pprint(*args, **kargs):
    kargs = {
        **kargs,
        "console": STDERR,
    }
    rich.pretty.pprint(*args, **kargs)


async def run(uri: str):
    debug = ArkDebugger()
    with rich.live.Live(console=debug.console) as l:
        async with debug.connect(uri):

            # enter you code here

            # await debug.execute_and_wait_paused(
            #     debugger.continue_to_location(
            #         location=debugger.Location(
            #             script_id=next(iter(debug.scripts)),
            #             line_number=15,
            #             column_number=0,
            #         ),
            #     )
            # )
            win = ArkDebuggerLive(debug)
            await win.update()
            l.update(win.layout)


def loggers_level(modules: typing.Iterable[str], level: int):
    for m in modules:
        logging.getLogger(m).setLevel(level)


def main(
    uri="ws://localhost:19015",
    verbose=False,
):
    try:
        if verbose:
            loggers_level(["trio_cdp", "main"], logging.DEBUG)
        trio.run(run, uri, restrict_keyboard_interrupt_to_checkpoints=True)
    except ArkConnectError as e:
        LOG.error(e)


if __name__ == "__main__":
    rich.traceback.install(show_locals=True, width=None)
    main(verbose=True)
